package com.example.visitedsys.FileConfig;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;


/**
 * @author  SongPeng
 * @date  2021/11/21 16:24
 * @version 1.0
 */

/**
 * FastDFS客户端包装类
 *
 *
 */
@Component
public class FastDFSClient {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String uploadFile(MultipartFile file) throws IOException {
        if (file != null) {
            byte[] bytes = file.getBytes();
            long fileSize = file.getSize();
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            return this.uploadFile(bytes, fileSize, extension);
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @param bytes     文件字节
     * @param fileSize  文件大小
     * @param extension 文件扩展名
     * @return 返回文件路径（卷名和文件名）
     */
    public String uploadFile(byte[] bytes, long fileSize, String extension) {
        ByteArrayInputStream fileBytes = new ByteArrayInputStream(bytes);
        // 元数据
        Set<MetaData> metaDataSet = new HashSet<MetaData>();
        metaDataSet.add(new MetaData("dateTime", LocalDateTime.now().toString()));
        StorePath storePath = fastFileStorageClient.uploadFile(fileBytes, fileSize, extension, metaDataSet);
        String trackerList="http://localhost:8080/";
        String url=trackerList+storePath.getFullPath();
        return url;
    }

}
